package com.manong.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.manong.aspect.AutoFill;
import com.manong.entity.Notice;
import com.manong.entity.Order;
import com.manong.entity.Shop;
import com.manong.service.OrderService;
import com.manong.service.ShopService;
import com.manong.utils.JwtUtils;
import com.manong.utils.Result;
import com.manong.vo.query.NoticeVo;
import com.manong.vo.query.OrderVo;
import com.manong.vo.query.ShopVo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
@RequestMapping("/api/order")
public class OrderController {
    @Resource
    private OrderService orderService;
    @Resource
    private ShopService shopService;

    @Resource
    private HttpServletRequest request;
    @Resource
    private JwtUtils jwtUtils;
    /**
     * 查询订单列表
     * @param shopVo
     * @return
     */
    @GetMapping("/list")
    public Result list(ShopVo shopVo){
        IPage<Shop> page = new Page<Shop>();
        page.setCurrent(shopVo.getPageNo());
        page.setSize(shopVo.getPageSize());
        shopVo.setStatus(1);
        shopService.findOrderListByUsername(page,shopVo);
        return Result.ok(page);
    }

    /**
     * @param order
     * @return
     */
    @AutoFill(menu = "订单管理", type = "添加")
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('sys:order:add')")
    public Result add(@RequestBody Order order){
        order.setCode("OR"+System.currentTimeMillis());
        if(orderService.save(order)){
            return Result.ok().message("添加成功");
        }else{
            return Result.error().message("添加失败");
        }
    }

    @AutoFill(menu = "订单管理", type = "结款")
    @PutMapping("/update")
    @PreAuthorize("hasAuthority('sys:order:edit')")
    public Result update(@RequestBody Shop shop){
        shop.setPayStatus(1);
        shop.setPayTime(new Date());
        shop.setPayUser(jwtUtils.getUsernameFromToken(request.getHeader("token")));
        //调用修改方法
        if(shopService.updateById(shop)){
            return Result.ok().message("操作成功");
        }
        //返回数据
        return Result.error().message("操作失败");
    }

    @AutoFill(menu = "订单管理", type = "删除")
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:order:delete')")
    public Result delete(@PathVariable Long id){
        if(orderService.deleteById(id)){
            return Result.ok().message("删除成功");
        }else{
            return Result.error().message("删除失败");
        }
    }
}
